import React, { useState, useEffect } from "react";
import style from "./style.module.scss";
import { getexplore } from "../../Api";
import { Link } from "react-router-dom";

const rest = () => {
  const warpEle = document.querySelector(`.${style.explore_warp}`);
  const children = Array.from(warpEle.children);
  let cloumCount = 4; // 共几列 每列隔14
  let cloumHArr = []; // 每列高
  for (let i = 0; i < cloumCount; i++) {
    cloumHArr[i] = 0;
  }
  children.forEach(el => {
    let minH = cloumHArr[0]; // 最矮列
    let minIndex = 0; // 最矮列下标
    for (let i = 0; i < cloumCount; i++) {
      if (cloumHArr[i] < minH) {
        minH = cloumHArr[i];
        minIndex = i;
      }
    }
    el.style.top = `${minH}px`;
    el.style.left = `${minIndex * (272 + 14)}px`;
    cloumHArr[minIndex] += el.offsetHeight + 20;
  });
  let maxH = Math.max(...cloumHArr);
  warpEle.style.height = `${maxH}px`;
};

const Eitem = props => {
  return (
    <div className={style.item_warp}>
      <Link to={`/play/${props.id}`}>
        <h5>{props.uname}</h5>
        <p className={style.title}>{props.title}</p>
        <img src={props.img} alt="pic" />
        <div className={style.info}>
          {`# ${props.sort}  # ${props.tag}  ${props.time}`}
        </div>
        <p className={style.count}>
          <span>{Object.keys(props.count).length - 1}</span>评论
        </p>
      </Link>
    </div>
  );
};

let page = 1;
let flag = true;
let finish = false;
function scroll(setposts, setfinish, type, key) {
  const loadmark = document.querySelector(`.${style.loadTip}`);
  const breact = loadmark.getBoundingClientRect();
  const { top, bottom } = breact;
  if (top >= 0 && bottom < window.innerHeight) {
    if (flag && !finish) {
      flag = false;
      getexplore(type, { page: page + 1, ...key }).then(res => {
        if (res && res.posts) {
          page = page + 1;
          setposts(prevposts => {
            flag = true;
            return [...prevposts, ...res.posts];
          });
        } else {
          finish = true;
          setfinish(finish);
        }
      });
    }
  }
}

const Explore = ({ match }) => {
  let type = "explore";
  let key = {};
  if (match.path === "/explore") {
    type = "explore";
  } else {
    type = "search";
    key.key = match.params.key;
  }
  const [posts, setposts] = useState([]);
  const [isfinish, setfinish] = useState(false);

  useEffect(() => {
    getexplore(type, key).then(res => {
      if (res.posts) {
        setposts(res.posts);
      }
    });
  }, []);

  useEffect(() => {
    rest();
  });

  useEffect(() => {
    const addScroll = _ => {
      scroll(setposts, setfinish, type, key);
    };
    window.addEventListener("scroll", addScroll);
    return () => {
      window.removeEventListener("scroll", addScroll);
    };
  });

  return (
    <div className={style.explore}>
      <div className={style.explore_warp}>
        {posts.map((post, index) => {
          return <Eitem key={index} {...post} />;
        })}
      </div>
      {isfinish ? (
        <div data-type="loading" className={style.loadTip}>
          没有更多了
        </div>
      ) : (
        <div data-type="loading" className={style.loadTip}>
          加载中...
        </div>
      )}
    </div>
  );
};

export default (props) => <Explore {...props} key={props.location.pathname}></Explore>;
